<template>
  <div>
    <el-card class=".box-card">
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
        v-has="`btn.Trademark.add`"
      >
        添加品牌
      </el-button>
      <!-- 表格组件:用于展示已有的品牌数据 -->
      <el-table style="margin: 10px 0" border :data="trademarkArr">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName">
          <template #="{ row, $index }">
            <pre style="color: black">{{ row.tmName }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img
              :src="row.logoUrl"
              alt="图片不存在"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}吗？`"
              width="250px"
              icon="Delete"
              @confirm="removeTradeMark(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="getHasTrademark"
        @size-change="handler"
      />
    </el-card>
    <!-- 对话框组件：添加或修改已有品牌的业务的时候使用 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      @close="closeDialog"
    >
      <!-- 表单 -->
      <el-form
        style="width: 80%"
        label-width="100px"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            class="avatar-uploader"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽：显示底部按钮 -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type {
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type'
import { ElMessage, type UploadProps } from 'element-plus'

//当前页码 每页展示数据条数
let pageNo = ref<number>(1)
let limit = ref<number>(3)
//存储已有品牌数据的总数
let total = ref<number>(0)
//存储已有品牌数据
let trademarkArr = ref<TradeMark[]>([])
//控制对话框的显示和隐藏
let dialogFormVisible = ref<boolean>(false)
//定义收集新增品牌的数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
//获取表单对象
let formRef = ref()

//获取已有品牌
const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}
//组件挂载完毕:发送请求获取已有品牌数据
onMounted(() => {
  getHasTrademark()
})
//分页器页码大小发生变化的回调
const handler = () => {
  getHasTrademark()
}
//点击添加品牌的回调
const addTrademark = () => {
  //对话框显示
  dialogFormVisible.value = true
  //收集的数据清空
  trademarkParams.id = null
  trademarkParams.logoUrl = ''
  trademarkParams.tmName = ''
}
//点击编辑按钮的回调
const updateTrademark = (row: TradeMark) => {
  //对话框显示
  dialogFormVisible.value = true
  //数据回显
  Object.assign(trademarkParams, row)
}
//点击取消按钮的回调
const cancel = () => {
  //对话框隐藏
  dialogFormVisible.value = false
}
//点击确认按钮的回调:添加或修改品牌(接口201：修改操作无法完成)
const confirm = async () => {
  //发送请求前需要校验所有表单项：返回一个promise对象，只有校验全部通过，再执行后面的代码
  await formRef.value.validate()
  //发送请求进行添加或更新操作
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code == 200) {
    //关闭对话框
    dialogFormVisible.value = false
    //消息提示
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
    //再次发送请求获取已有品牌数据：根据新增|修改跳转到对应页码
    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    //关闭对话框
    dialogFormVisible.value = false
    //消息提示
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
//upload组件上传图片成功前的钩子：在图片上传成功之前触发，上传文件前可以约束文件类型和大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //约束:上传文件的格式png|jpg|gif 大小小于4M
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的文件大小应该小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件务必是PNG|JPG|GIF',
    })
    return false
  }
}
//upload组件上传图片成功后的钩子:收集上传图片的地址
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  //收集上传图片的地址
  trademarkParams.logoUrl = response.data
  //清除LOGO的校验结果
  formRef.value.clearValidate('logoUrl')
}
//对话框关闭的回调函数
const closeDialog = () => {
  //清除所有校验结果
  nextTick(() => {
    formRef.value.clearValidate(['tmName', 'logoUrl'])
  })
}
//校验品牌名称的函数
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称需要大于等于两位'))
  }
}
//校验品牌LOGO的校验规则
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
//表单校验的规则对象
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}
//点击气泡框删除按钮的回调(接口201：删除操作无法完成)
const removeTradeMark = async (id: number) => {
  let result: any = await reqDeleteTrademark(id)
  if (result.code == 200) {
    //提示信息
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
    //重新获取已有的品牌数据
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
